package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.core.BaseServlet;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.User;
import com.itheima.service.system.DeptService;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.DeptServiceImpl;
import com.itheima.service.system.impl.UserServiceImpl;
import com.itheima.utils.BeanUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/system/user/*")
public class UserController extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    private DeptService deptService = new DeptServiceImpl();
    public Object list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if (StringUtil.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtil.isEmpty(pageSize)) {
            pageSize = "10";
        }
        PageInfo<User> pageInfo = userService.pageQuery(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        request.setAttribute("page", pageInfo);
        return "/WEB-INF/pages/system/user/list.jsp";
    }

    public Object toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Dept> list = deptService.findAll();
        request.setAttribute("deptList", list);
        return "/WEB-INF/pages/system/user/add.jsp";
    }
    public Object save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        userService.save(user);
        return "/system/user/list";
    }
    public Object toEdit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        User user = userService.findById(id);
        request.setAttribute("user", user);
        List<Dept> list = deptService.findAll();
        request.setAttribute("deptList", list);
        return "/WEB-INF/pages/system/user/update.jsp";
    }
    public Object edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class, "yyyy-MM-dd");
        userService.update(user);
        return "/system/user/list";
    }
    public Object delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] ids = request.getParameterValues("id");
        userService.delete(ids);
        return "/system/user/list";
    }
}
